<template>
    <div>
        <div class="search">
            <input type="text" class="searchInput" placeholder="输入城市名或拼音" v-model="keyWord">
        </div>
        <div class="search-content" ref="wrapper" v-show="keyWord">
            <div>
                <ul>
                    <div class="border-topbottom" v-for="item of list" :key="item.id" @click="hanleCityClick(item.name)">{{item.name}}</div>
                    <div v-show="hasNoData" style="text-align:center;padding-top:70%;">
                        没有搜索到相关结果
                    </div>
                </ul>
            </div>
            
        </div>
    </div>
</template>

<style lang="stylus" scoped>
@import '~styles/variable.styl';

.search {
    height: 0.72rem;
    padding: 0.1rem;
    background-color: $bgColor;

    input {
        position: relative;
        bottom: 0.2rem;
        height: 0.62rem;
        width: 100%;
        line-height: 0.62rem;
        text-align: center;
        border-radius: 0.06rem;
        border-width: 0;
        color: #666;
        padding: 0 0.1rem;
    }
}

.search-content {
    z-index: 1;
    position: absolute;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    background-color :white;
    color :#666;
}

.border-topbottom {
    padding:.2rem;
    border-bottom :1px solid #ccc;
}
</style>

<script>
import Bscroll from "better-scroll";
export default {
  name: "CitySearch",
  data() {
    return {
      keyWord: "",
      list: [],
      timer: null
    }
  },
    mounted() {
        this.scroll = new Bscroll(this.$refs.wrapper);
    },
  props: {
    cities: Object
  },
  computed:{
      hasNoData(){
          return !this.list.length
      }
  },
  methods:{
       hanleCityClick(city){
        //   复杂做法
        //   this.$store.dispatch("changeCity",city);
        this.$store.commit("changeCity",city);
        this.$router.push("/")


      }
  },
  watch: {
    keyWord() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if(!this.keyWord){
          this.list = [];
          return
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (
              value.spell.indexOf(this.keyWord) > -1 ||
              value.name.indexOf(this.keyWord) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  }
};
</script>


